<template>
  <div class="page_role app-container" v-loading="loading">
    <cfCard title="" class="page-container-search bottom12">
      <el-form slot="content" :model="searchParams" ref="searchPrams" size="small" :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="searchParams.roleName" placeholder="请输入角色名称" clearable v-search="handleSearch" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="searchParams.roleKey" placeholder="请输入权限字符" clearable v-search="handleSearch" />
        </el-form-item>
        <el-form-item label="状 态" prop="status">
          <el-select v-model="searchParams.status" placeholder="角色状态" clearable @change="handleSearch">
            <el-option v-for="dict in sysNormalDisable" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker v-model="searchParams.createTime" value-format="yyyy-MM-dd" type="daterange" style="width: 220px;" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleSearch"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </cfCard>
    <cfCard title='岗位列表' hasTable :tableObj='tableDataObj' class='page_house-container-bottom'>
      <!--表格区域-->
      <template slot='btn'>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:role:add']">新增</el-button>
        <!-- <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:role:edit']">修改</el-button> -->
        <!-- <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:role:remove']">删除</el-button> -->
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:role:export']">导出</el-button>
      </template>
      <template slot='content'>
        <cfTable ref="cfTable" :tableDataObj='tableDataObj' :tableData='roleList' @handleSelectionChange="handleSelectionChange">
          <template slot="status">
            <el-table-column label='状 态' width='100px' align='center'>
              <el-switch slot-scope="scope" v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
            </el-table-column>
          </template>
          <template slot="createTime">
            <el-table-column label='创建时间' width='180px'>
              <span slot-scope="scope">{{ parseTime(scope.row.createTime) }}</span>
            </el-table-column>
          </template>
          <template slot='operate'>
            <el-table-column label='操 作' width='160px' align='right' v-if="hasPermiOr(['system:role:edit', 'system:role:remove'])">
              <span slot-scope='scope'>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']" >修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" class="delete-span" @click="handleDelete(scope.row)" v-hasPermi="['system:role:remove']" >删除</el-button>
                <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:role:edit']">
                  <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="handleDataScope" icon="el-icon-circle-check" v-hasPermi="['system:role:edit']">数据权限</el-dropdown-item>
                    <el-dropdown-item command="handleAuthUser" icon="el-icon-user" v-hasPermi="['system:role:edit']">分配用户</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </el-table-column>
          </template>
        </cfTable>
        <pagination :total='queryParams.total' :page.sync='queryParams.pageNum' :limit.sync='queryParams.pageSize' @pagination='getListFn'/>
      </template>
    </cfCard>
    <component :is='dialogObj.component' :dialogObj="dialogObj" v-if="dialogObj.visible" @refresh="getListFn"></component>
    <cfPageDialog v-if='pageDialogObj.visible' :pageDialog='pageDialogObj'>
      <authUser v-if='pageDialogObj.visible' :pageDialogObj='pageDialogObj'></authUser>
    </cfPageDialog>
  </div>
</template>

<script>
import { listRole, getRole, delRole, changeRoleStatus, exportRole } from "@/api/system/role";
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
import updateDialog from "./updateDialog"
import roleAssign from "./roleAssign"
import authUser from "./authUser"
export default {
  name: "Role",
  components: {updateDialog, roleAssign, authUser},
  data() {
    return {
      loading: false,
      ids: [],/**选中数组*/ 
      single: true, /**非单个禁用*/ 
      multiple: true, /**非多个禁用*/ 
      roleList: [], /**角色表格数据*/ 
      queryParams: { /**是否显示弹出层（数据权限）*/ 
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      searchParams: { /**查询参数*/ 
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      },
      tableDataObj: {
        id: 'id',
        showSelection: false,
        showIndex: true,
        defaultExpandAll: false,
        treeProps: {children: 'children', hasChildren: 'hasChildren'},
        option: [
          {id: 1, label: '角色编号', prop: 'roleId', show: 1, needSlot: false},
          {id: 2, label: '角色名称', prop: 'roleName', show: 1, needSlot: false},
          {id: 3, label: '权限字符', prop: 'roleKey', show: 1, needSlot: false},
          {id: 4, label: '显示顺序', prop: 'roleSort', align: 'center', show: 1, needSlot: false},
          {id: 5, label: '状态', prop: 'status', show: 1, needSlot: true},
          {id: 6, label: '创建时间', prop: 'createTime', show: 1, needSlot: true},
        ]
      },
      dialogObj: {
        visible: false,
        id: '',
        title: '',
        width: '528px',
        type: 'add',
        component: ''
      },
      pageDialogObj: {
        visible: false,
        id: '',
        title: '',
      }
    };
  },
  async created() {
    await this.getSysNormalDisable();
    this.getListFn();
  },
  methods: {
    async getListFn() { /** 查询角色列表 */
      this.loading = true;
      const data = {
        ...this.searchParams,
        ...this.queryParams
      }
      delete data.createTime;
      if(Array.isArray(this.searchParams.createTime) && this.searchParams.createTime.length) {
        data.params = {
          beginTime: this.searchParams.createTime[0],
          endTime: this.searchParams.createTime[1]
        }
      }
      const res = await listRole(data);
      if(res.code == 200) {
        this.roleList = res.rows;
        this.queryParams.total = res.total;
      }
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    handleStatusChange(row) {  // 角色状态修改
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗？').then(async()=> {
        this.loading = true;
        const res = await changeRoleStatus(row.roleId, row.status);
        if(res.code == 200) {
          this.$modal.msgSuccess(text + "成功");
        }
        setTimeout(() => {
          this.loading = false;
        }, 500);
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleSearch() {  /** 搜索按钮操作 */
      this.queryParams.pageNum = 1;
      this.queryParams.total = 0;
      this.roleList = [];
      this.getListFn();
    },
    handleReset() {  /** 重置按钮操作 */
      this.resetForm("searchPrams", () => {
        this.handleSearch();
      });
    },
    handleSelectionChange(selection) { /**多选框选中数据*/ 
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length!=1
      this.multiple = !selection.length;
    },
    handleCommand(command, row) {   /**更多操作触发*/ 
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    handleAdd() { /** 新增按钮操作 */
      this.dialogObj.visible = true;
      this.dialogObj.title = '添加角色';
      this.dialogObj.id = '';
      this.dialogObj.component = 'updateDialog';
    },
    handleUpdate(row) { /** 修改按钮操作 */
      this.dialogObj.visible = true;
      this.dialogObj.id = row.roleId;
      this.dialogObj.title = "修改角色";
      this.dialogObj.component = "updateDialog";
    },
    handleDataScope(row) { /** 分配数据权限操作 */
      this.dialogObj.visible = true;
      this.dialogObj.id = row.roleId;
      this.dialogObj.title = '分配数据权限';
      this.dialogObj.component = 'roleAssign';
    },
    handleAuthUser(row) {  /** 分配用户操作 */
      this.pageDialogObj.visible = true;
      this.pageDialogObj.id = row.roleId;
      this.pageDialogObj.title = '分配用户';
    },
    handleDelete(row) { /** 删除按钮操作 */
      const roleIds = row.roleId || this.ids;
      this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(async()=> {
        this.loading = true;
        const res = await delRole(roleIds);
        if(res.code == 200) {
          this.handleSearch();
          this.$modal.msgSuccess("删除成功");
        }
        setTimeout(() => {
          this.loading = false;
        }, 500);
      }).catch(() => {});
    },
    async handleExport() { /** 导出按钮操作 */
      this.loading = true;
      const res = await exportRole(this.queryParams);
      if(res.data && res.status == 200) {
        this.downloadFilesFn(res, `角色列表${this.formatDate('', true, '-')}.xlsx`);
      }
      setTimeout(() => {
        this.loading = false;
      }, 500);
    }
  }
};
</script>